package com.zwcl.common.core.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author: Jame
 * @Date: 2019/11/19 10:24
 * @Description: excel解析监听器
 * 每解析一行会回调invoke()方法
 * 整个excel解析结束会执行doAfterAllAnalysed()方法
 */
public class ExcelListener<T> extends AnalysisEventListener<T> {

    private List<T> list = new ArrayList<>();

    private Consumer<List<T>> consumer;

    private int pageSize;

    public ExcelListener(Consumer<List<T>> consumer, int pageSize) {
        this.consumer = consumer;
        this.pageSize = pageSize;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        list.add(t);
        if (list.size() == pageSize) {
            consumer.accept(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (list.size() > 0) {
            consumer.accept(list);
        }
    }
}
